#!/bin/bash

function usage()
{
	echo -e "\nUsage: $0 <on|off|xHZ>\n"
	echo -e "  for example:"
	echo -e "    $0 on    --- turn on PWM"
	echo -e "    $0 off   --- turn off PWM"
	echo -e "    $0 st    --- get the PWM status"
	echo -e "    $0 30    --- turn on PWM, and set the frequency to 30HZ\n"
}

function pwm_timer_operate()
{
	local opt=$1
	local sysfs_pwmgpio="/sys/class/leds/pwm-gpio"

	local pwmtrigger_tmp=$(cat ${sysfs_pwmgpio}/trigger | awk -F ' ' '{for(i=1;i<=NF;i++){if($i ~/\[/){print $i}}}')
	local pwmtrigger=${pwmtrigger_tmp:1:${#pwmtrigger_tmp}-2}

	# The unit of delay_on/delay_off is "ms"
	case ${opt} in
		"on")
			if [[ ${pwmtrigger} != "timer" ]]; then
				echo timer > ${sysfs_pwmgpio}/trigger
				echo 500 > ${sysfs_pwmgpio}/delay_on
				echo 500 > ${sysfs_pwmgpio}/delay_off
			fi

			let perios_ms=$(cat ${sysfs_pwmgpio}/delay_on)+$(cat ${sysfs_pwmgpio}/delay_off)
			let freq=1000/${perios_ms}
			echo "[INFO] PWM has turn ON, frequency ${freq}HZ"
			;;
		"off")
			echo none > ${sysfs_pwmgpio}/trigger
			echo "[INFO] PWM has turn OFF"
			;;
		"st")
			if [[ ${pwmtrigger} != "timer" ]]; then
				echo "[INFO] PWM is OFF"
			else
				let perios_ms=$(cat ${sysfs_pwmgpio}/delay_on)+$(cat ${sysfs_pwmgpio}/delay_off)
				let freq=1000/${perios_ms}
				echo "[INFO] PWM is ON, frequency ${freq}HZ"
			fi
			;;
		*)
			# Frequency specified must be an integer number
			if [[ ! ${opt} =~ ^[1-9][0-9]*$ ]]; then
				echo "[ERROR] Unsupport operation option: ${opt}"
				usage
				exit 1
			fi

			if [[ ${opt} -lt 1 || ${opt} -gt 1000 ]]; then
				echo "[ERROR] Unsupport frequency ${opt}"
				usage
				exit 1
			fi

			if [[ ${pwmtrigger} != "timer" ]]; then
				echo timer > ${sysfs_pwmgpio}/trigger
			fi

			let period_ms=1000/${opt}
			let on_ms=${period_ms}/2
			let off_ms=${period_ms}-${on_ms}

			echo ${on_ms} > ${sysfs_pwmgpio}/delay_on
			echo ${off_ms} > ${sysfs_pwmgpio}/delay_off

			echo "[INFO] PWM has turn ON, frequency=${opt}"
			echo "  Period_ms=${period_ms}"
			echo "  ON_ms=${on_ms}"
			echo "  OFF_ms=${off_ms}"
			;;
	esac
}

##################################################################

if [[ $# -lt 1 ]]; then
	usage
	exit 1
fi

if [[ $(id -u) -ne 0 ]]; then
	echo -e "[ERROR] Please run as root!"
	usage
	exit 1
fi

pwm_timer_operate $1
